package com.g2room.myuall.grap.univ;

import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.PreparedStatement;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.g2room.driving.util.HtmlUtil;
import com.g2room.myuall.grap.univ.po.UnivPo;
import com.g2room.myuall.util.DbUtil;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;

public class GrapTsData {
	//http://gkcx.eol.cn/ads/gaokao/tszy-1.shtml
	String url = "http://gkcx.eol.cn/ads/gaokao/tszy###.shtml";
	
	public static void main(String[] args) {
//		for(int i =0; i<7; i++) {
//		}
		new GrapTsData().getDetail(0);
	}
	
	/**
	 * 获取列表数据
	 * @param url
	 * @throws FailingHttpStatusCodeException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public void getDetail(int i) {
		String grapUrl = url.replace("###", i == 0 ? "" : "-"+i);
		System.out.println("Name==" + grapUrl);
		try {
			Document doc = new GenericMyuall().getDoc(grapUrl);
			// 获取建校时间和类别
			Elements tableEls = doc.getElementsByTag("table");
			String univName = "";
			for(Element tableEl : tableEls) {
				Elements trEls = tableEl.getElementsByTag("tr");
				for(Element tr : trEls) {
					Elements tdEls = tr.getElementsByTag("td");
					if(tdEls.size() > 2) continue;
					String val = "";
					if((tr.text().contains("第") || tr.text().contains("全国高校")) && (tr.text().contains("批"))) continue;
					if(tdEls.size() == 1) {
						val = tdEls.get(0).text();
					} else {
						univName = tdEls.get(0).text();
						val = tdEls.get(1).text();
					}
					if(null == val || val.trim().length() ==0 || val.equals("专业名称")) continue;
					System.out.println(univName + "==" + val);
					insert2Db(univName, val, i);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static PreparedStatement  ps = null;
	int sqlCount = 0;
	public void insert2Db(String univName, String majorName, int type) {
		try {
			if(sqlCount == 0) ps = DbUtil.getConn().prepareStatement("insert into univ_tszy(univName,majorName,type) values(?,?,?)");
			// name,sourceUrl,description,position,personNum,tuition,photo,summary,univUrl,category,createDate,nameEn
			ps.setString(1, univName);
			ps.setString(2, majorName);
			ps.setInt(3, type);
			ps.execute();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
